<template>
  <view class="container">
    <!-- 顶部装饰 -->
    <view class="header">
      <view class="header-content">
        <text class="title">购物车</text>
        <text class="subtitle" v-if="cartList.length > 0">共 {{ cartList.length }} 件商品</text>
      </view>
      <view class="header-decoration">
        <view class="decoration-circle"></view>
        <view class="decoration-circle"></view>
      </view>
    </view>

    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y>
      <view v-if="cartList.length === 0" class="empty-state">
        <image src="/static/cart/empty-cart.png" mode="aspectFit" class="empty-icon"/>
        <text class="empty-text">购物车还是空的</text>
        <button class="go-shopping-btn" @tap="goShopping">去逛逛</button>
      </view>

      <view v-else class="cart-items">
        <view 
          v-for="item in cartList" 
          :key="item.id" 
          class="cart-item"
        >
          <!-- 选择框 -->
          <checkbox 
            :checked="selectedItems.includes(item.id!) && isItemAvailable(item)" 
            @tap="isItemAvailable(item) && toggleSelect(item.id!)"
            class="checkbox"
            :disabled="!isItemAvailable(item)"
          />

          <!-- 商品信息 -->
          <view class="item-content" @tap="goToDetail(item.product?.id)">
            <image 
              :src="item.productSKUVO?.image || item.product?.image || 'https://fsp-1326500412.cos.ap-chengdu.myqcloud.com/default.png'"
              mode="aspectFill" 
              class="product-image"
            />
            <view class="product-info">
              <text class="product-name">{{ item.product?.name || '商品名称' }}</text>
              <text class="sku-info">{{ item.productSKUVO?.quantity || '规格' }}</text>
              <view class="price-quantity">
                <view class="price-status">
                  <text class="price">¥{{ item.productSKUVO?.price?.toFixed(2) || '0.00' }}</text>
                  <text v-if="!isItemAvailable(item)" class="status-text">已售完</text>
                </view>
                <text class="quantity-text">x{{ item.quantity || 0 }}</text>
              </view>
            </view>
          </view>

          <!-- 删除按钮 -->
          <view class="delete-btn" @tap="deleteItem(item)">
            <image src="/static/cart/delete.png" mode="aspectFit" class="delete-icon"/>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 底部结算栏 -->
    <view class="footer" v-if="cartList.length > 0">
      <view class="select-all">
        <checkbox 
          :checked="isAllSelected" 
          @tap="toggleSelectAll"
          class="checkbox"
        />
        <text>全选</text>
      </view>
      <view class="total-info">
        <text class="total-label">合计：</text>
        <text class="total-price">¥{{ totalPrice.toFixed(2) }}</text>
      </view>
      <button class="checkout-btn" @tap="checkout" :disabled="selectedItems.length === 0">
        结算({{ selectedItems.length }})
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import { listMyCartVoByPageUsingPost, deleteCartUsingPost, addOrderBatchUsingPost } from '@/backend';
import { tokenStore } from '@/store/tokenStore';
import type { API } from '../../backend/typings';

const tokenStoreInstance = tokenStore();
const cartList = ref<API.CartVO[]>([]);
const selectedItems = ref<number[]>([]);
const pageNum = ref(1);
const pageSize = ref(10); // 首次加载10条
const loadMoreSize = ref(5); // 加载更多时5条
const hasMore = ref(true);
const loading = ref(false);

// 是否全选
const isAllSelected = computed(() => {
  const availableItems = cartList.value.filter(item => isItemAvailable(item));
  return availableItems.length > 0 && 
         availableItems.every(item => selectedItems.value.includes(item.id!));
});

// 计算总价
const totalPrice = computed(() => {
  return cartList.value.reduce((total, item) => {
    if (selectedItems.value.includes(item.id!)) {
      return total + (item.quantity || 0) * (item.productSKUVO?.price || 0);
    }
    return total;
  }, 0);
});

// 判断商品是否可用（已上架且有库存）
const isItemAvailable = (item: API.CartVO) => {
  return item.productSKUVO?.status !== 'inactive' && 
         (item.productSKUVO?.stock || 0) > 0;
};

// 获取购物车列表
const fetchCartList = async (refresh = false) => {
  if (loading.value) return;

  if (refresh) {
    pageNum.value = 1;
    hasMore.value = true;
    cartList.value = []; // 清空现有数据
  }

  loading.value = true;
  try {
    const params = {
      current: pageNum.value,
      pageSize: refresh ? pageSize.value : loadMoreSize.value,
      sortField: 'createTime',
      sortOrder: 'desc',
      // 添加必要的查询参数
      searchText: '',
      userId: undefined // 后端会从token中获取
    };

    
    const res = await listMyCartVoByPageUsingPost(params);

    if (res?.code === 0 && res?.data?.records) {
      const newRecords = res.data.records;
      cartList.value = refresh ? newRecords : [...cartList.value, ...newRecords];
      
      // 判断是否还有更多数据
      const total = res.data.total || 0;
      pageNum.value++; // 更新页码
      const currentTotal = pageNum.value * pageSize.value;
      hasMore.value = currentTotal < total;
      
      // 如果当前页数据量小于pageSize，说明没有更多数据了
      if (newRecords.length < pageSize.value) {
        hasMore.value = false;
      }

      // 清理已失效的选中项
      selectedItems.value = selectedItems.value.filter(id => 
        cartList.value.some(item => item.id === id)
      );
    } else {
      hasMore.value = false;
      console.warn('获取购物车列表失败：', res?.message);
      uni.showToast({
        title: res?.message || '获取购物车列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取购物车列表失败：', error);
    uni.showToast({
      title: '获取购物车列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    if (refresh) {
      // 停止下拉刷新动画
      uni.stopPullDownRefresh();
    }
  }
};

// 切换选择状态
const toggleSelect = (id: number) => {
  const item = cartList.value.find(item => item.id === id);
  if (!item || !isItemAvailable(item)) return;

  const index = selectedItems.value.indexOf(id);
  if (index === -1) {
    selectedItems.value.push(id);
  } else {
    selectedItems.value.splice(index, 1);
  }
};

// 全选/取消全选
const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedItems.value = [];
  } else {
    selectedItems.value = cartList.value
      .filter(item => isItemAvailable(item))
      .map(item => item.id!);
  }
};

// 删除商品
const deleteItem = async (item: API.CartVO) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除这个商品吗？',
    success: async (res) => {
      if (res.confirm && item.id) {
        try {
          const result = await deleteCartUsingPost({ id: item.id });
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            await fetchCartList();
          }
        } catch (error) {
          console.error('删除失败：', error);
        }
      }
    }
  });
};

// 去购物
const goShopping = () => {
  uni.switchTab({
    url: '/pages/home/home'
  });
};

// 去商品详情
const goToDetail = (productId?: number) => {
  if (!productId) return;
  uni.navigateTo({
    url: `/pages/product/detail?id=${productId}`
  });
};

// 结算
const checkout = async () => {
  if (selectedItems.value.length === 0) {
    uni.showToast({
      title: '请选择商品',
      icon: 'none'
    });
    return;
  }

  // 准备选中的商品信息
  const selectedProducts = cartList.value.filter(item => 
    selectedItems.value.includes(item.id!)
  );

  // 跳转到确认订单页面
  const cartInfo = {
    products: selectedProducts,
    cartIds: selectedItems.value
  };

  uni.navigateTo({
    url: `/pages/order/cart-confirm?cartInfo=${encodeURIComponent(JSON.stringify(cartInfo))}`
  });
};

// 下拉刷新处理
const onPullDownRefresh = () => {
  selectedItems.value = []; // 清空选中状态
  fetchCartList(true);
};

onShow(() => {
  const token = tokenStoreInstance.getToken;

  if (!token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/profile/profile'
      });
    }, 1500);
    return;
  }
  
  // 确保每次显示页面时都重新加载数据
  fetchCartList(true);
});

onMounted(() => {
  const token = tokenStoreInstance.getToken;
  if (token) {
    fetchCartList(true);
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f8f8f8;
  padding-bottom: 120rpx;
}

.header {
  background: #fff;
  padding: 20rpx 32rpx 30rpx;
  position: relative;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333;
  position: relative;
  z-index: 1;
}

.subtitle {
  font-size: 24rpx;
  color: #999;
}

.header-decoration {
  position: absolute;
  right: 32rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  gap: 12rpx;
}

.decoration-circle {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  opacity: 0.8;
}

.decoration-circle:last-child {
  opacity: 0.4;
}

.cart-list {
  padding: 0 20rpx;
}

.cart-item {
  background: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.checkbox {
  margin-right: 20rpx;
  transform: scale(0.8);
}

.item-content {
  flex: 1;
  display: flex;
  gap: 20rpx;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 12rpx;
  background: #f5f5f5;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}

.sku-info {
  font-size: 24rpx;
  color: #999;
  margin: 8rpx 0;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8rpx;
}

.price-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.price {
  font-size: 32rpx;
  color: #ff5722;
  font-weight: 600;
}

.status-text {
  font-size: 24rpx;
  color: #999;
}

.quantity-text {
  font-size: 28rpx;
  color: #666;
  font-weight: 500;
}

.delete-btn {
  padding: 20rpx;
}

.delete-icon {
  width: 36rpx;
  height: 36rpx;
}

.empty-state {
  padding: 120rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-icon {
  width: 240rpx;
  height: 240rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping-btn {
  width: 240rpx;
  height: 80rpx;
  background: #ff5722;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.total-info {
  flex: 1;
  text-align: right;
  margin-right: 20rpx;
}

.total-label {
  font-size: 28rpx;
  color: #666;
}

.total-price {
  font-size: 36rpx;
  color: #ff5722;
  font-weight: 600;
}

.checkout-btn {
  width: 200rpx;
  height: 72rpx;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 28rpx;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkout-btn:disabled {
  background: #ccc;
  opacity: 0.8;
}
</style> 